package com.ledim.ledimview;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.ledim.activity.EpisodesActivity;
import com.ledim.bean.LedimChoiceCardBean;
import com.ledim.bean.RoomAddPlayListResponse;
import com.ledim.bean.SubmediaEpisodesResponse;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.service.LedimApiServiceUtils;
import com.ledim.service.LedimHttpObserver;
import com.ledim.utils.ConstantUtil;
import com.ledim.utils.FrescoUtil;
import com.ledim.utils.LedimBaseUtils;
import com.ledim.utils.LedimFunctionUtils;
import com.ledim.utils.ToastUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.core.bean.IVideo;
import java.text.SimpleDateFormat;

/**
 * Created by GeekZooStudio on 2015/10/10.
 */
public class SearchListViewItemView extends LinearLayout {

    private static final int POSITIVE = 180001;
    private static final int TV = 181031;
    public static final int LAUNCH_MODE_ALBUM = 2;
    private SimpleDraweeView mImage;
    private View mLayout;
    private View mRightLayout;
    private TextView mTitle;
    private TextView mTime;
    private TextView mHoster;
    private TextView mNum;
    private TextView mZheng;
    private TextView mXiao;
    private Context mContext;
    private boolean mAddPlay;
    private LedimChoiceCardBean card;
    private String mMediaId;
    private String mSubMediaId;
    private String mRoomId;

    public SearchListViewItemView(Context context) {
        super(context);
        mContext = context;
    }

    public SearchListViewItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public SearchListViewItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    //绑定数据
    public void bindData(LedimChoiceCardBean card, String roomId) {
        this.card = card;
        this.mAddPlay = !TextUtils.isEmpty(roomId);
        mRoomId = roomId;
        String url = card.link.replaceAll("app://medias/", "");
        mMediaId = url.substring(0, url.indexOf("/"));
        mSubMediaId = card.link.substring(card.link.lastIndexOf("/") + 1, card.link.length());
        init();
    }

    /**
     * 初始化界面
     */
    private void init() {
        mLayout = findViewById(R.id.all_layout);
        mRightLayout = findViewById(R.id.right_layout);
        mImage = (SimpleDraweeView) findViewById(R.id.search_result_list_img);
        mTitle = (TextView) findViewById(R.id.search_result_list_title);
        //时间
        mTime = (TextView) findViewById(R.id.search_result_list_time);
        mHoster = (TextView) findViewById(R.id.search_result_list_hoster);
        mNum = (TextView) findViewById(R.id.search_result_list_num);
        mZheng = (TextView) findViewById(R.id.search_result_list_score_zheng);
        mXiao = (TextView) findViewById(R.id.search_result_list_score_xiao);

        //设置up主
        TextView mUp = (TextView) findViewById(R.id.tv_search_up);
        if (mAddPlay && card.source == 2) {
            mUp.setVisibility(View.VISIBLE);
            mUp.setText("UP主：" + card.upName);
        } else {
            mUp.setVisibility(View.GONE);
        }

        if (card.isClick) {
            mLayout.setBackgroundColor(Color.parseColor("#FEFBBD"));
            mRightLayout.setBackgroundColor(Color.parseColor("#FEFBBD"));
        } else {
            mLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
            mRightLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }

        if (card.photo != null && !TextUtils.isEmpty(card.photo.thumb)) {
            FrescoUtil.loadUrl(card.photo.thumb, mImage);
        }
        mTitle.setText(Html.fromHtml(card.title));
        if (TextUtils.isEmpty(card.album.playCount)) {
            mNum.setText("");
        } else {
            Long count = Long.parseLong(card.album.playCount);
            if (count > 0) {
                mNum.setText(LedimFunctionUtils.formatGoldCount(count) + "次");
            } else {
                mNum.setText("");
            }
        }

        if (card.subtitle.equals("综艺") || card.subtitle.equals("纪录片")) {
            if (card.album.starring != null && card.album.starring.length > 0) {
                mHoster.setVisibility(View.VISIBLE);
                mHoster.setText("参演明星：" + LedimBaseUtils.mapArraysToString(card.album.starring));
            } else {
                mHoster.setVisibility(View.GONE);
            }
            if (card.album.isEnd == 1) {//完结
                if (card.album.episodes == 0) {
                    mTime.setVisibility(View.GONE);
                } else {
                    mTime.setVisibility(View.VISIBLE);
                    mTime.setText(card.album.episodes + "期全");
                }
            } else {
                if (card.album.nowEpisodes == 0) {
                    mTime.setVisibility(View.GONE);
                } else {
                    mTime.setText("更新至" + card.album.nowEpisodes + "期");
                }
            }
        } else if (card.subtitle.equals("电视剧") || card.subtitle.equals("动漫")) {
            if (card.album.starring != null && card.album.starring.length > 0) {
                mHoster.setVisibility(View.VISIBLE);
                mHoster.setText("参演明星：" + LedimBaseUtils.mapArraysToString(card.album.starring));
            } else {
                mHoster.setVisibility(View.GONE);
            }
            if (card.album.isEnd == 1) {//完结
                if (card.album.nowEpisodes == 0) {
                    mTime.setVisibility(View.GONE);
                } else {
                    mTime.setVisibility(View.VISIBLE);
                    mTime.setText(card.album.nowEpisodes + "集全");
                }

            } else {
                if (card.album.nowEpisodes == 0) {
                    mTime.setVisibility(View.GONE);
                } else {
                    mTime.setVisibility(View.VISIBLE);
                    mTime.setText("更新至" + card.album.nowEpisodes + "集");
                }

            }
        } else if (card.subtitle.equals("娱乐") || card.subtitle.equals("资讯") ||
                card.subtitle.equals("音乐")) {
            if (card.album.starring != null && card.album.starring.length > 0) {
                mHoster.setVisibility(View.VISIBLE);
                mHoster.setText("参演明星：" + LedimBaseUtils.mapArraysToString(card.album.starring));
            } else {
                mHoster.setVisibility(View.GONE);
            }
            if (card.album.releaseDate != null) {
                mTime.setVisibility(View.VISIBLE);
                SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
                String time = sf.format(Long.parseLong(card.album.releaseDate));
                mTime.setText("年份：" + time.substring(0, 5));
            }
        } else if (card.subtitle.equals("电影")) {
            if (card.album.starring != null && card.album.starring.length > 0) {
                mHoster.setVisibility(View.VISIBLE);
                mHoster.setText("参演明星：" + LedimBaseUtils.mapArraysToString(card.album.starring));
            } else {
                mHoster.setVisibility(View.GONE);
            }
            if (card.album.releaseDate != null) {
                mTime.setVisibility(View.VISIBLE);
                SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
                String time = sf.format(Long.parseLong(card.album.releaseDate));
                mTime.setText("年份：" + time.substring(0, 5));
            }

        }

        if (card.album.rating != null && card.album.rating.length() > 0) {
            if (!LedimBaseUtils.isNumeric(card.album.rating)) {
                String[] figures = card.album.rating.split("\\.");
                mZheng.setText(figures[0] + ".");
                mXiao.setText(figures[1]);
            } else {
                mZheng.setText(card.album.rating);
                mXiao.setVisibility(View.INVISIBLE);
            }
        }

        if (mAddPlay) {
            mLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    //上报数据
                    LedimFunctionUtils.reportSearchItemEvent(LeDimAnalysisUtils.ROOM_SEARCH_CODE, card);

                    if (mMediaId.equals("0")) {
                        mLayout.setBackgroundColor(Color.parseColor("#FEFBBD"));
                        LedimApiServiceUtils.addRoomPlayListByVid(mRoomId, mMediaId, mSubMediaId, card.title,
                                card.video.duration == null ? "0" : card.video.duration, observer);
                    } else {
                        //                        mMediasTypeMediaSub_mediaEpisodesGetModel.getMediaLists(SearchListViewItemView.this, mMediaId,mSubMediaId,2,true,0,mAddPlay, 1);

                        //                        switch (card.album.varietyShow) {
                        //                            case VARITYSHOW://栏目1
                        //                                mMediasTypeMediaSub_mediaEpisodesGetModel.getMediaLists(SearchListViewItemView.this, mMediaId,mSubMediaId,2,true,0,mAddPlay, 2);
                        //                                break;
                        //                            default:
                        if (!TextUtils.isEmpty(card.album.videoType)) {
                            switch (Integer.parseInt(card.album.videoType)) {
                                case POSITIVE://正片
                                case TV://TV版
                                    //电影，电视剧，动漫,纪录片
                                    if (card.album.category == ConstantUtil.ChannelType.film ||
                                            card.album.category == ConstantUtil.ChannelType.tv ||
                                            card.album.category ==
                                                    ConstantUtil.ChannelType.cartoon ||
                                            card.album.category ==
                                                    ConstantUtil.ChannelType.record ||
                                            card.album.category == ConstantUtil.ChannelType.self ||
                                            card.album.category ==
                                                    ConstantUtil.ChannelType.variety) {
                                        LedimApiServiceUtils.getMediaLists(mMediaId, mSubMediaId, 2, 0, 2, 1, mediaListObserver);
                                        return;
                                    }
                            }
                        }
                        LedimApiServiceUtils.getMediaLists(mMediaId, mSubMediaId, 2, 0, 1, 1, mediaListObserver);
                    }
                }
            });

        } else {
            mLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //上报数据
                    LedimFunctionUtils.reportSearchItemEvent(LeDimAnalysisUtils.ALBUM_SEARCH_CODE, card);
                    IVideo video = new IVideo();
                    video.setmVid(0);
                    LetvSDK.getInstance()
                           .play(mContext, video, false, card);//card这是一个CARD对象，调用此方法后将CARD传给AlbumPlayActivity中
                }
            });
        }

    }

    private LedimHttpObserver mediaListObserver =
            new LedimHttpObserver<SubmediaEpisodesResponse>() {
                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                }

                @Override
                public void onNext(SubmediaEpisodesResponse response) {
                    super.onNext(response);
                    if (response != null && response.success) {
                        if (response.data.size() != 0) {
                            if (response.data.size() == 1) {
                                card.isClick = true;
                                if (card.isClick) {
                                    mLayout.setBackgroundColor(Color.parseColor("#FEFBBD"));
                                    mRightLayout.setBackgroundColor(Color.parseColor("#FEFBBD"));
                                } else {
                                    mLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
                                    mRightLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));
                                }
                                LedimApiServiceUtils.addRoomPlayList(mRoomId, response.data, observer);
                            } else {
                                card.isClick = false;

                                Intent intent = new Intent(mContext, EpisodesActivity.class);
                                if (card.subtitle.equals("综艺") || card.subtitle.equals("纪录片")) {
                                    intent.putExtra(EpisodesActivity.EPISODES, -1);
                                } else if (card.subtitle.equals("电视剧") ||
                                        card.subtitle.equals("动漫")) {
                                    if (card.album.nowEpisodes == 0) {
                                        intent.putExtra(EpisodesActivity.EPISODES, response.paged.total);
                                    } else {
                                        intent.putExtra(EpisodesActivity.EPISODES, card.album.nowEpisodes);
                                    }
                                } else if (card.subtitle.equals("娱乐") ||
                                        card.subtitle.equals("资讯") ||
                                        card.subtitle.equals("音乐")) {
                                    intent.putExtra(EpisodesActivity.EPISODES, -1);
                                } else if (card.subtitle.equals("电影")) {
                                    intent.putExtra(EpisodesActivity.EPISODES, -1);
                                } else {
                                    //教育
                                    intent.putExtra(EpisodesActivity.EPISODES, -1);
                                }

                                if (TextUtils.isEmpty(card.media)) {
                                    if (!TextUtils.isEmpty(card.link)) {
                                        String link = card.link.replace("app://medias/", "");
                                        String[] s = link.split("/");
                                        if (s.length > 1) {
                                            card.media = s[0];
                                            card.submedia = s[1];
                                        }
                                    }
                                }
                                intent.putExtra(EpisodesActivity.SUBMEDIAID, card.submedia);
                                intent.putExtra(EpisodesActivity.MEDIAID, card.media);
                                intent.putExtra(EpisodesActivity.ROOM_ID, mRoomId);
                                intent.putExtra(EpisodesActivity.ALBUM, card.album.getLedimAlbumBean());
                                mContext.startActivity(intent);
                            }
                        }
                    }

                }
            };
    private LedimHttpObserver observer = new LedimHttpObserver<RoomAddPlayListResponse>() {
        @Override
        public void onError(Throwable e) {
            super.onError(e);
            ToastUtil.toast("添加失败,请稍候重试");
        }

        @Override
        public void onNext(RoomAddPlayListResponse response) {
            super.onNext(response);
            if (response != null && response.success) {
                ToastUtil.toast("好了,大王");
            } else {
                if (response.code == 404) {
                    ToastUtil.toast("内容太高能,添加失败");
                } else {
                    ToastUtil.toast("添加失败,请稍候重试");
                }
            }

        }
    };
}
